# encoding: utf-8
# pylint: disable=too-many-arguments
"""
Application execution related tasks for Invoke.
"""
import logging

logging.basicConfig(filename='/usr/local/logs/ucloud-agent.log', filemode='w', level=logging.DEBUG)

import sys

reload(sys)
sys.setdefaultencoding('utf8')

try:
    from invoke import ctask as task
except ImportError:  # Invoke 0.13 renamed ctask to task
    from invoke import task


@task(default=True)
def run(
        context,
        host='0.0.0.0',
        port=5000,
        development=False,
        install_dependencies=True,
        upgrade_db=False
):
    """
    Run Beetel-Agent.
    """
    if install_dependencies:
        context.invoke_execute(context, 'app.dependencies.install')
    if upgrade_db:
        context.invoke_execute(context, 'app.db.upgrade')
        if development:
            context.invoke_execute(
                context,
                'app.db.init_development_data',
                upgrade_db=False,
                skip_on_failure=True
            )

    from app import create_app

    application = create_app(
        flask_config='development' if development else 'production'
    )

    if application.config['socketio_app']:
        socketio_app = application.config['socketio_app']
        socketio_app.run(
            app=application,
            host=host,
            port=port
        )
    else:
        application.run(
            host=host,
            port=port
        )
